import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { is } from 'immutable'

import { Button, Form, Modal, message, Spin, Breadcrumb, Icon } from 'antd'
const createForm = Form.create;
const FormItem = Form.Item;

import { WeaTab, WeaErrorPage, WeaTools, WeaSearchGroup } from 'ecCom'

import CustomerContact from '../CustomerContact.js'
import LeaveMessage from '../customerCard/LeaveMessage.js'
import ViewContacter from '../data/ViewContacter.js'
import ViewSellChance from '../data/ViewSellChance.js'
import AddContacterModal from '../data/AddContacterModal.js'
import * as CardManageAction from '../../actions/cardManage'

class CardManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        }
    }
    componentDidMount() {
        const { actions, paramsData } = this.props;
        actions.setParamsFromLeft(paramsData);

        actions.getContacterInfo(paramsData);//联系人信息
        actions.getSellChanceInfo(paramsData);//销售机会信息

        actions.contactLogCondition();
        actions.contacterCardCondition();
        actions.leaveMessageCondition();
        actions.sellchanceCardCondition();
    }
    componentWillReceiveProps(nextProps) {
        const { actions } = this.props;
        if (!is(this.props.rightInfos, nextProps.rightInfos)) {
            actions.setTabKey("1");
        }
        const oldCusid = this.props.paramsData.customerId;
        const newCusid = nextProps.paramsData.customerId;

        const oldChanceid = this.props.paramsData.chanceid;
        const newChanceid = nextProps.paramsData.chanceid;
        if (oldCusid != newCusid || oldChanceid != newChanceid) {
            const { paramsData } = nextProps;
            actions.setParamsFromLeft(paramsData);
            actions.getContacterInfo(paramsData);//联系人信息
            actions.getSellChanceInfo(paramsData);//销售机会信息
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return !is(this.props.rightInfos, nextProps.rightInfos) ||
            !is(this.props.selectTabKey, nextProps.selectTabKey) ||
            !is(this.props.showSearchAd, nextProps.showSearchAd) ||
            !is(this.props.contactLogCondition, nextProps.contactLogCondition) ||
            !is(this.props.contacterCardCondition, nextProps.contacterCardCondition) ||
            !is(this.props.leaveMessageCondition, nextProps.leaveMessageCondition) ||
            !is(this.props.sellchanceCardCondition, nextProps.sellchanceCardCondition) ||
            !is(this.props.highSearchParamsAd, nextProps.highSearchParamsAd) ||
            !is(this.props.orderFields, nextProps.orderFields) ||
            !is(this.props.baseParams, nextProps.baseParams) ||
            !is(this.props.contacterCardData, nextProps.contacterCardData) ||
            !is(this.props.sellChanceCardData, nextProps.sellChanceCardData) ||
            !is(this.props.addContacterCondition, nextProps.addContacterCondition);
    }

    render() {
        const { actions, rightInfos, selectTabKey, showSearchAd, highSearchParamsAd, baseParams, contacterCardData, sellChanceCardData, 
            addContacterCondition,type } = this.props;
        return (
            <div className="crm-right-tab">
                <div className="sellchancemain-right-top">
                    <Breadcrumb>
                        {
                            rightInfos.get('titleInfo').toJS().sellChanceNameHtml ? 
                                <Breadcrumb.Item><span dangerouslySetInnerHTML={{ __html: rightInfos.get('titleInfo').toJS().sellChanceNameHtml }}></span></Breadcrumb.Item>
                                :<div></div>
                        }
                        <Breadcrumb.Item><span dangerouslySetInnerHTML={{ __html: rightInfos.get('titleInfo').toJS().crmNameHtml }}></span></Breadcrumb.Item>
                        <Breadcrumb.Item><span dangerouslySetInnerHTML={{ __html: rightInfos.get('titleInfo').toJS().managerNameHtml }}></span></Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <WeaTab
                    buttonsAd={this.getTabButtonsAd()}  //高级搜索底部button
                    searchType={['base', 'advanced']}
                    {...this.getHighSearchs() }
                    setShowSearchAd={bool => { actions.setShowSearchAd(bool) }}
                    hideSearchAd={() => actions.setShowSearchAd(false)}
                    showSearchAd={showSearchAd}
                    onSearch={v => { actions.changeSearchParamsAd() }}
                    selectedKey={selectTabKey}
                    datas={rightInfos.get('tabInfo').toJS()}
                    keyParam='key'
                    onChange={this.changeTab.bind(this)}
                />
                {
                    selectTabKey == "1" &&
                    <div className="contact-logs-container">
                        <CustomerContact ref="contactlogs" type={type} params={baseParams.toJS()} />
                    </div>
                }
                {
                    selectTabKey == "2" &&
                    <div className="contact-logs-container">
                        <ViewContacter data={contacterCardData} />
                    </div>
                }
                {
                    selectTabKey == "3" &&
                    <div className="contact-logs-container">
                        <LeaveMessage ref="leaveMessage" params={baseParams.toJS()} />
                    </div>
                }
                {
                    selectTabKey == "4" &&
                    <div className="contact-logs-container">
                        <ViewSellChance data={sellChanceCardData} />
                    </div>
                }
                {selectTabKey == "2" && <AddContacterModal ref="addContacterModal" addCondition={addContacterCondition} customerId={rightInfos.get('customerId')} all={this.props} actions={actions} />}
            </div>
        )
    }
    changeTab(key) {
        const { actions, paramsData } = this.props;
        actions.setTabKey(key);
        actions.setParamsFromLeft(paramsData);
    }
    getTabButtonsAd() {
        const { actions } = this.props;
        return [
            (<Button type="primary" onClick={() => { actions.changeSearchParamsAd(); actions.setShowSearchAd(false) }}>搜索</Button>),
            (<Button type="ghost" onClick={() => { actions.saveOrderFields({}) }}>重置</Button>),
            (<Button type="ghost" onClick={() => { actions.setShowSearchAd(false) }}>取消</Button>)
        ]
    }
    getHighSearchs() {
        const { selectTabKey, actions, highSearchParamsAd } = this.props;
        if (selectTabKey == "1") {
            return {
                searchsBaseValue: highSearchParamsAd.get('remark'),
                buttons: [""],
                searchsAd: <Form horizontal>{this.getSearchsCondotion()}</Form>,
                onSearchChange: v => { actions.saveOrderFields({ remark: { name: 'remark', value: v } }) }
            }
        }
        if (selectTabKey == "2") {
            return {
                searchsBaseValue: highSearchParamsAd.get('firstname'),
                buttons: [<span title="新增" size="small" onClick={this.AddContacter} style={{ fontSize: "16px", marginRight: "5px" }}><Icon type="plus-square" /></span>],
                searchsAd: <Form horizontal>{this.getSearchsCondotion()}</Form>,
                onSearchChange: v => { actions.saveOrderFields({ firstname: { name: 'firstname', value: v } }) }
            }
        }
        if (selectTabKey == "3") {
            return {
                searchsBaseValue: highSearchParamsAd.get('remarkM'),
                buttons: [""],
                searchsAd: <Form horizontal>{this.getSearchsCondotion()}</Form>,
                onSearchChange: v => { actions.saveOrderFields({ remarkM: { name: 'remarkM', value: v } }) }
            }
        }
        if (selectTabKey == "4") {
            return {
                searchsBaseValue: highSearchParamsAd.get('subject'),
                buttons: [""],
                searchsAd: <Form horizontal>{this.getSearchsCondotion()}</Form>,
                onSearchChange: v => { actions.saveOrderFields({ subject: { name: 'subject', value: v } }) }
            }
        }
    }
    getSearchsCondotion() {
        const { contactLogCondition, contacterCardCondition, leaveMessageCondition, sellchanceCardCondition, selectTabKey } = this.props;
        let highCondition = [];
        if (selectTabKey == "1") {
            highCondition = contactLogCondition.toJS()
        } else if (selectTabKey == "2") {
            highCondition = contacterCardCondition.toJS()
        } else if (selectTabKey == "3") {
            highCondition = leaveMessageCondition.toJS()
        } else if (selectTabKey == "4") {
            highCondition = sellchanceCardCondition.toJS()
        }
        let group = [];
        highCondition.map(c => {
            let items = [];
            c.items.map(field => {
                items.push({
                    com: (<FormItem
                        label={`${field.label}`}
                        labelCol={{ span: `${field.labelcol}` }}
                        wrapperCol={{ span: `${field.fieldcol}` }}>
                        {WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                    </FormItem>),
                    colSpan: 1
                })
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} col={1} />)
        });
        return group
    }
    AddContacter = () => {
        const { actions } = this.props;
        actions.addContacterForm({ operation: 'add' });
        this.refs.addContacterModal.visible = true;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return (
            <WeaErrorPage msg={hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！"} />
        );
    }
}

CardManage = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(CardManage);

CardManage = createForm({
    onFieldsChange(props, fields) {
        props.actions.saveOrderFields({ ...props.orderFields.toJS(), ...fields });
    },
    mapPropsToFields(props) {
        return props.orderFields.toJS();
    }
})(CardManage);


function mapStateToProps(state) {
    const { crmCardManage } = state;
    return {
        selectTabKey: crmCardManage.get('selectTabKey'),
        showSearchAd: crmCardManage.get('showSearchAd'),
        contactLogCondition: crmCardManage.get('contactLogCondition'),
        contacterCardCondition: crmCardManage.get('contacterCardCondition'),
        leaveMessageCondition: crmCardManage.get('leaveMessageCondition'),
        sellchanceCardCondition: crmCardManage.get('sellchanceCardCondition'),
        highSearchParamsAd: crmCardManage.get('highSearchParamsAd'),
        orderFields: crmCardManage.get('orderFields'),
        baseParams: crmCardManage.get('baseParams'),
        contacterCardData: crmCardManage.get('contacterCardData'),
        sellChanceCardData: crmCardManage.get('sellChanceCardData'),
        addContacterCondition: crmCardManage.get('addContacterCondition'),
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({ ...CardManageAction }, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CardManage);


